// import {
//   config
// } from '../config'

var app = getApp();

/** 相同url网络POST请求最小时间间隔 */
const minRequestSpace = 1000;

class HTTP {
  route = ''
  constructor(nroute) {
    if (nroute) {
      this.route = nroute
    } else {
      this.route = ''
    }
  }

  request({
    url,
    data = {},
    method = 'GET',
    headers = {}
  }) {
    if (this.route) {
      headers['route'] = this.route;
    }

    if (!app) {
      app = getApp();
    }
    if (!app) {
      app = wx.app;
    }

    let that = this;
    return new Promise((resolve, reject) => {
      this._request({
        url,
        resolve,
        reject,
        data,
        headers,
        method
      })
      // if (app.hasToken()){
      //   this._request({ url, resolve, reject, data, headers, method})
      // } else {
      //   // app.login(() => {
      //   //   this._request({ url, resolve, reject, data, headers, method })
      //   // })
      // }
    })
  }

  _request({
    url,
    resolve,
    reject,
    data = {},
    headers,
    method = 'GET'
  }) {
    const that = this;
    let contentType = "application/json";
    if (method == "POST") {
      contentType = "application/x-www-form-urlencoded";
    }

    wx.wxp.request({
      url: config.api_base_url + url,
      method: method,
      data: data,
      header: Object.assign({}, headers, {
        'content-type': contentType
        // 'token': wx.getStorageSync("userInfo").token || '',
        // 'account': wx.getStorageSync("userInfo").phone || ''
      })
    }).then(res => {
      // console.log(res);
      resolve(res.data);
    }).catch(err => {
      console.error(err);
      that._showError("网络错误");
      reject(err);
    })
  }

  _showError(errMsg) {
    wx.showToast({
      title: errMsg,
      icon: 'none',
      duration: 2000
    })
  }
}

export {
  HTTP
}